'''
@Author: 冯浩
@Date: 2019-12-01 22:40:22
@LastEditors: 冯浩
@LastEditTime: 2019-12-08 22:28:05
@FilePath: \bob_develop\fluent_python\示例5_10.py
'''


def tag(name: str, *content, cls: str = None, **attrs) -> str:
    '''生成一个或者多个HTML标签'''
    if cls is not None:
        attrs['class'] = cls

    if attrs:  # 将字典格式整理成目标格式字串,join函数内部可以将列表的[]去掉
        attr_str = ''.join(
            [' %s="%s"' % (attr, value)
             for attr, value in sorted(attrs.items())]
        )
    else:
        attr_str = ''

    if content:
        return '\n'.join(
            '<%s%s>%s</%s>' % (name, attr_str, c, name) for c in content
        )
    else:
        return '<%s%s />' % (name, attr_str)


if __name__ == "__main__":
    print(tag('br'))  # <br />
    print(tag('br', 'hello'))  # <br>hello</br>
    print(tag('br', 'hello', 'world'))  # <br>hello</br>  <br>world</br>
    print(tag('p', 'hello', id='33'))  # <p id="33">hello</p>

    print(tag('p', 'hello', 'world', cls='sidebar'))
    '''<p class="sidebar">hello</p>  
    <p class="sidebar">world</p>'''

    print(tag(content='testing', name='img'))
    ''' <img content="testing" /> 注意这里很特殊
    调用tag函数时,即便是第一个定位参数,也能作为关键词参数传入'''

    mytag = {
        'name': 'img', 'title': 'sunset boulevard',
        'src': 'sunset.jpg', 'cls': 'framed'}
    print(tag(**mytag))
    '''<img class="framed" src="sunset.jpg" title="sunset boulevard" />
    在mytag前面加上**,字典中的所有元素作为单个参数传入,同名键会绑定到对应的具名参数上,余下的被**attrs捕获
    '''

    mytag2 = {
        'title': 'sunset boulevard',
        'src': 'sunset.jpg', 'cls': 'framed'}
    print(tag('img', '我是内容', **mytag2))
    # <img class="framed" src="sunset.jpg" title="sunset boulevard">我是内容</img>
